package com.azt.back.freemarker;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.azt.back.util.ContextUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 后台管理员权限许可 用来判断有没有权限
 */
@Component("func_perm")
public class FuncPermDirective implements TemplateDirectiveModel {
	/**
	 * PARAM_URL
	 */
	public static final String PARAM_URL = "url";

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		String url = DirectiveUtils.getString(PARAM_URL, params);
		boolean pass = false;
		if (StringUtils.isBlank(url)) {
			// url为空，则认为有权限。
			pass = true;
		} else {
			List<String> functions = ContextUtils.getFunctions();
			for (String func : functions) {
				if (null != func && !"".equals(func)) {
					if (url.startsWith(func)) {
						pass = true;
						break;
					}
				}
			}
		}
		if (pass) {
			body.render(env.getOut());
		}
	}
}
